<?php
namespace control;
/*
*考勤统计类
*/

use JetBrains\PhpStorm\NoReturn;

class clockStatisticsClass extends adIndexClass
{
    private const page = 'clockStatistics';
    private const table = 'work_sign';
    private const title = '考勤记录';

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "员工" => selectMultiple(array("name" => "stid[]",'multiple'=>true, "table" => "staff",  "where" => " state <> '离职' ", 'class' => 'width200', 'sqlField' => 'name', 'sqlId' => 'stid')),
                    "日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //控件
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }

        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'stid'      => [
                        'name'  => "姓名",
                        'width' => 200,
                    ],
                    'department' => [
                        'name'  => "部门",
                        'width' => 200,
                    ],
                    'signTime'  => [
                        'name'  => '打卡记录',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'type'         => [
                        'name'  => '类型',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'address'          => [
                        'name'  => '地址',
                        'width' => 300,
                    ],
                    'text'    => [
                        'name'  => '备注',
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        $and = "1=1";
        if ($this->post('stid')) {
            $and .= " and stid in ('".implode("','",$this->post('stid'))."')";
        }
        if ($this->post('createTime')) {
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and date(signTime) >='{$timeArr[0]}' and  date(signTime) <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'signTime',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = $and;
        $page = $this->page(array("table" => self::table,'order'=>$orderBy['orderBy'],'where'=>$where));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            //表格控件区
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case "department":
                        $job = query('job'," id = '$array[jobId]'");
                        $row[] = departmentClass::getTypeName($job['departmentId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] .$button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '你还没有导入的权限';
        }else {
            $exampleData[] = ['YM202111090001','徐三','2021-11-16 08:00:00'];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '员工编号'=>$example[0],
                            '员工姓名'=>$example[1],
                            '打卡时间'=>$example[2],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = $this->control['name'] . "下载了考勤记录导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = '你还没有导入的权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    if ($cell['员工编号']){
                        $staff = query("staff", "orderNo = '$cell[员工编号]'");
                    }else{
                        $staff = query("staff", "name = '$cell[员工姓名]'");
                    }

                    $field = [
                        "jobId" => $staff['jobId'],
                        "stid" => $staff['stid'],
                        "signTime" => $cell['打卡时间'],
                        "type" => '导入',
                    ];
                    $annotation = [
                        'stid' => '员工',
                        'signTime' => '打卡时间',
                    ];
                    $rules = [
                        'stid' => 'required',
                        'signTime' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= "\n第【{$row_list}】行，" . $vt->getErrs()[0];
                    } else {
                        //查看范围
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "\n第【{$row_list}】行导入成功";
                        } else {
                            $text .= "\n第【{$row_list}】行导入失败：编辑失败";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . "导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条，详情如下：" . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by signTime desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            foreach ($result as $array){
                $job = query('job'," id = '$array[jobId]'");
                $staff = query('staff'," stid = '$array[stid]'");
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '员工编号'=>$staff['orderNo'],
                            '员工姓名'=>$staff['name'],
                            '部门'=>departmentClass::getTypeName($job['departmentId']),
                            '打卡时间'=>$array['signTime'],
                            '类型'=>$array['type'],
                            '地址'=>$array['address'],
                            '备注'=>$array['text'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了考勤统计表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "考勤统计表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /*列表页-查询条件*/
    public function collectOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "员工" => selectMultiple(array("name" => "stid[]",'multiple'=>true, "table" => "staff",  "where" => " state <> '离职' ", 'class' => 'width200', 'sqlField' => 'name', 'sqlId' => 'stid')),
                    "月份" => text(array("name" => "month",'laydate' => ['type' => 'month'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 考勤汇总
     *
     */
    public function collect(): bool|string
    {
        $html = $this->collectOptions(false);
        //控件
        $button = "";
        //导出
        if ($this->power('clockCollect', "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportDataCollect'><span class='spanButton'>导出</span></a>\n";
        }
        return $this->homeFun($this->searchExecute([
            'html'         => $html,
            'layout'       => 'pop',
            'toolButton'   => $button,
            'option'      => '{fixed:true,row:2}'
        ]));
    }

    /**
     * 考勤汇总
     * @return bool|string
     */
    public function collectSearch(): bool|string
    {
        //全等查询数组
        $equal = array(
        );
        $like = array(
        );
        $and = " and state <> '离职' ";
        if ($this->post('stid')) {
            $and .= " and stid in ('".implode("','",$this->post('stid'))."')";
        }
        //排序
        $orderBy = $this->orderBy(array(
            "search" => $this->post('orderBy')??null,
            "default" => "月份降序",
            "array" => array(
                "month" => array("desc" => "月份降序", "site" => 5),
            ),
        ));
        $month = $this->post('month')?:date("Y-m");
        $_SESSION['clockCollect']['month'] = $month;
        $workSignCheckClass = new workSignCheckClass();
        $lastMonthTime = $workSignCheckClass->lastMonthTime($month);//最后一天时间 获取有效薪酬规则
        //休息日
        $holiday = $this->getHoliday(date("Y",strtotime($month.'-01')));
        //获取查询结果
        $where = search(array("=" => $equal, 'like' => $like)) . $and;
        $page = $this->page(array("table" => 'staff', "where" => $where, "order" => 'time asc'));
        $_SESSION['clockCollect']['collect'] = $page['fullSql'];
        //获取表头
        $tr='';
        //获取记录
        foreach ($page['array'] as $k=>$array) {
            $list = $k+1;
            $department = self::findStaffDepartment($array['stid']);
            //根据员工选择器的值和当前员工的部门，职位，员工ID求交集
            $idColloection = $this->staffCombination(true,$array['stid']);
            //考勤规则
            $clockRule = query('clock_rule', " (concat(',',replace(selector,';',','),',') regexp concat(',',replace('{$idColloection}',',',',|,'),','))>0 and state = '启用' and UNIX_TIMESTAMP(startTime) <=UNIX_TIMESTAMP('{$lastMonthTime}') order by startTime desc");
            //本月工作日
            $workDayResult = $workSignCheckClass->getWorkDay($month, $clockRule['workDayId']);
            $workDay = $workDayResult['workDay']?:[];
            //本月实际考勤天数
            $actualDays         = find([
                    'table'  => "work_sign_single",
                    'field'  => "IFNULL(count(id),0) as num",
                    'single' => " date_format(date, '%Y-%m') = '$month' and stid = '$array[stid]' ",
                ])['num'] ?? 0;
            //正常天数
            $normal         = find([
                    'table'  => "work_sign_single",
                    'field'  => "IFNULL(count(id),0) as num",
                    'single' => " date_format(date, '%Y-%m') = '$month' and stid = '$array[stid]' and sign_start <= start_time and sign_end >= end_time ",
                ])['num'] ?? 0;
            //异常天数
            $abnormal = $actualDays-$normal;
            //工时
            $workingHours       = find([
                    'table'  => "work_sign_single",
                    'field'  => "IFNULL(sum(lawHour),0) as lawHour,IFNULL(sum(workHour),0) as workHour",
                    'single' => " date_format(date, '%Y-%m') = '$month' and stid = '$array[stid]' ",
                ]);
            //异常次数
            $number       = find([
                'table'  => "work_sign_single",
                'field'  => "IFNULL(sum(late),0) as late,IFNULL(sum(early),0) as early,IFNULL(sum(is_leave),0) as is_leave,IFNULL(sum(miss),0) as miss",
                'single' => " date_format(date, '%Y-%m') = '$month' and stid = '$array[stid]' ",
            ]);
            //外出
            $work_out         = find([
                    'table'  => "work_out",
                    'field'  => "IFNULL(sum(timestampdiff(hour,timeStart,timeEnd)),0) as total",
                    'single' => " date_format(timeStart, '%Y-%m') = '$month' and stid = '$array[stid]' and state = '成果确认' ",
                ])['total'] ?? 0;
            //出差
            $bussiness_trip         = find([
                    'table'  => "bussiness_trip",
                    'field'  => "IFNULL(sum(timestampdiff(hour,factStartTime,factEndTime)),0) as total",
                    'single' => " date_format(factStartTime, '%Y-%m') = '$month' and staffId = '$array[stid]' and state = '成果确认' ",
                ])['total'] ?? 0;
            //年假
            $annualLeave         = find([
                    'table'  => "work_holiday",
                    'field'  => "IFNULL(sum(hour),0) as total",
                    'single' => " date_format(startTime, '%Y-%m') = '$month' and stid = '$array[stid]' and state = '已通过' and type = '年假' ",
                ])['total'] ?? 0;
            //事假
            $compassionateLeave         = find([
                    'table'  => "work_holiday",
                    'field'  => "IFNULL(sum(hour),0) as total",
                    'single' => " date_format(startTime, '%Y-%m') = '$month' and stid = '$array[stid]' and state = '已通过' and type = '事假' ",
                ])['total'] ?? 0;
            //病假
            $sickLeave         = find([
                    'table'  => "work_holiday",
                    'field'  => "IFNULL(sum(hour),0) as total",
                    'single' => " date_format(startTime, '%Y-%m') = '$month' and stid = '$array[stid]' and state = '已通过' and type = '病假' ",
                ])['total'] ?? 0;
            //加班小时数，加班开始时间在本月即记为本月加班
            $workAddHour = find(array("table" => "work_add", "sum" => "hour", "where" => " stid = '" . $array['stid'] . "' and date_format(timeStart,'%Y-%m') = '$month' and state = '已通过' "));
            //工作日加班
            $workAddHourWeekday = find(array("table" => "work_add", "sum" => "hour", "where" => " stid = '" . $array['stid'] . "' and date_format(timeStart,'%Y-%m') = '$month' and state = '已通过' and date_format(timeStart,'%Y-%m-%d') in ('".implode("','",$workDay)."') "));
            //休息日加班
            $workAddHourRestDay = find(array("table" => "work_add", "sum" => "hour", "where" => " stid = '" . $array['stid'] . "' and date_format(timeStart,'%Y-%m') = '$month' and state = '已通过' and date_format(timeStart,'%Y-%m-%d') in ('".implode("','",$holiday['holiday'])."') "));
            //节假日加班
            $workAddHourFestival = find(array("table" => "work_add", "sum" => "hour", "where" => " stid = '" . $array['stid'] . "' and date_format(timeStart,'%Y-%m') = '$month' and state = '已通过' and date_format(timeStart,'%Y-%m-%d') in ('".implode("','",$holiday['festival'])."') "));
            //加班调休
            $exceedWorkHour = $workingHours['workHour'] > $workingHours['lawHour']?$workingHours['workHour'] - $workingHours['lawHour']:0;
            $compensatoryLeave = $workAddHour - $exceedWorkHour; //总加班时长-超出标准的工时=加班调休时长
            $tr .= <<<eof
                 <tr>
                    <td>{$list}</td>
                    <td>{$month}</td>
                    <td>{$array['name']}</td>
                    <td>{$department}</td>
                    <td>{$clockRule['team']}</td>
                    <td>{$workDayResult['dayNum']}</td><td>{$normal}</td><td>{$abnormal}</td><td>{$workingHours['lawHour']}</td><td>{$workingHours['workHour']}</td>
                    <td>{$number['late']}</td><td>{$number['early']}</td><td>{$number['is_leave']}</td><td>{$number['miss']}</td>
                    <td>{$work_out}</td><td>{$bussiness_trip}</td><td>{$annualLeave}</td><td>{$compassionateLeave}</td><td>{$sickLeave}</td>
                    <td>{$workAddHourWeekday}</td><td>{$workAddHourRestDay}</td><td>{$workAddHourFestival}</td><td>{$compensatoryLeave}</td>
                </tr>
eof;
        }

        $html = <<<eof
<table id="subjectTable" class="tableMany">
    <thead>
        <tr>
            <td rowspan="2" style="vertical-align:middle"></td>
            <td rowspan="2" style="vertical-align:middle">月份</td>
            <td rowspan="2" style="vertical-align:middle">姓名</td>
            <td rowspan="2" style="vertical-align:middle">部门</td>
            <td rowspan="2" style="vertical-align:middle">考勤组</td>
            <td colspan="5" class="center">概况</td>
            <td colspan="4" class="center">异常</td>
            <td colspan="5" class="center">假勤</td>
            <td colspan="4" class="center">加班</td>
        </tr>
        <tr>
            <td>工作天数</td><td>正常天数</td><td>异常天数</td><td>标准工时</td><td>实际工时</td>
            <td>迟到次数</td><td>早退次数</td><td>旷工次数</td><td>缺卡次数</td>
            <td>外出</td><td>出差</td><td>年假</td><td>事假</td><td>病假</td>
            <td>工作日加班</td><td>休息日加班</td><td>节假日加班</td><td>加班调休</td>
        </tr>
    </thead>
    <tbody>
     {$tr}
    </tbody>
</table>
<style>
.tableMany td:nth-child(1) {text-align: center;background-color: #f2f2f2;}
#subjectTable td{white-space:nowrap}
#subjectTable{margin-left: 0;}
.listForm{overflow: auto;width: calc(100%);}
</style>
eof;



        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form class='listForm' name='listForm'>" . $html . "</form>" . $page['button'];

        $json['html'] .= <<<eof
<script>
         
</script>
eof;

        return json_encode($json, 320);
    }
    /**
     * 获取当年的节假日
     */
    public function getHoliday($year): array
    {
        $holiday = query('holiday', " year = '$year'");
        $holidayArr = $holiday['workDay'] ? json_decode($holiday['workDay'], true) : [];//休息日数组
        $festivalArr = $holiday['festival'] ? json_decode($holiday['festival'], true) : [];//国定假数组
        return array('holiday' => $holidayArr, 'festival' => array_keys($festivalArr));
    }

    /**
     * 导出
     */
    public function exportDataCollect()
    {
        if (!$this->power('clockCollect', 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            $sql = $_SESSION['clockCollect']['collect'];
            $title = array("序号", "月份",'姓名','部门','考勤组','工作天数','正常天数','异常天数','标准工时','实际工时','迟到次数','早退次数','旷工次数','缺卡次数','外出','出差','年假','事假','病假','工作日加班','休息日加班','节假日加班','加班调休');
            $result = sqlFind($sql);
            if (is_array($result)) {
                $month = $_SESSION['clockCollect']['month'];
                $workSignCheckClass = new workSignCheckClass();
                $lastMonthTime = $workSignCheckClass->lastMonthTime($month);//最后一天时间 获取有效薪酬规则
                //休息日
                $holiday = $this->getHoliday(date("Y",strtotime($month.'-01')));
                foreach ($result as $k=>$array) {
                    $list = $k+1;
                    $department = self::findStaffDepartment($array['stid']);
                    //根据员工选择器的值和当前员工的部门，职位，员工ID求交集
                    $idColloection = $this->staffCombination(true,$array['stid']);
                    //考勤规则
                    $clockRule = query('clock_rule', " (concat(',',replace(selector,';',','),',') regexp concat(',',replace('{$idColloection}',',',',|,'),','))>0 and state = '启用' and UNIX_TIMESTAMP(startTime) <=UNIX_TIMESTAMP('{$lastMonthTime}') order by startTime desc");
                    //本月工作日
                    $workDayResult = $workSignCheckClass->getWorkDay($month, $clockRule['workDayId']);
                    $workDay = $workDayResult['workDay']?:[];
                    //本月实际考勤天数
                    $actualDays         = find([
                            'table'  => "work_sign_single",
                            'field'  => "IFNULL(count(id),0) as num",
                            'single' => " date_format(date, '%Y-%m') = '$month' and stid = '$array[stid]' ",
                        ])['num'] ?? 0;
                    //正常天数
                    $normal         = find([
                            'table'  => "work_sign_single",
                            'field'  => "IFNULL(count(id),0) as num",
                            'single' => " date_format(date, '%Y-%m') = '$month' and stid = '$array[stid]' and sign_start <= start_time and sign_end >= end_time ",
                        ])['num'] ?? 0;
                    //异常天数
                    $abnormal = $actualDays-$normal;
                    //工时
                    $workingHours       = find([
                        'table'  => "work_sign_single",
                        'field'  => "IFNULL(sum(lawHour),0) as lawHour,IFNULL(sum(workHour),0) as workHour",
                        'single' => " date_format(date, '%Y-%m') = '$month' and stid = '$array[stid]' ",
                    ]);
                    //异常次数
                    $number       = find([
                        'table'  => "work_sign_single",
                        'field'  => "IFNULL(sum(late),0) as late,IFNULL(sum(early),0) as early,IFNULL(sum(is_leave),0) as is_leave,IFNULL(sum(miss),0) as miss",
                        'single' => " date_format(date, '%Y-%m') = '$month' and stid = '$array[stid]' ",
                    ]);
                    //外出
                    $work_out         = find([
                            'table'  => "work_out",
                            'field'  => "IFNULL(sum(timestampdiff(hour,timeStart,timeEnd)),0) as total",
                            'single' => " date_format(timeStart, '%Y-%m') = '$month' and stid = '$array[stid]' and state = '成果确认' ",
                        ])['total'] ?? 0;
                    //出差
                    $bussiness_trip         = find([
                            'table'  => "bussiness_trip",
                            'field'  => "IFNULL(sum(timestampdiff(hour,factStartTime,factEndTime)),0) as total",
                            'single' => " date_format(factStartTime, '%Y-%m') = '$month' and staffId = '$array[stid]' and state = '成果确认' ",
                        ])['total'] ?? 0;
                    //年假
                    $annualLeave         = find([
                            'table'  => "work_holiday",
                            'field'  => "IFNULL(sum(hour),0) as total",
                            'single' => " date_format(startTime, '%Y-%m') = '$month' and stid = '$array[stid]' and state = '已通过' and type = '年假' ",
                        ])['total'] ?? 0;
                    //事假
                    $compassionateLeave         = find([
                            'table'  => "work_holiday",
                            'field'  => "IFNULL(sum(hour),0) as total",
                            'single' => " date_format(startTime, '%Y-%m') = '$month' and stid = '$array[stid]' and state = '已通过' and type = '事假' ",
                        ])['total'] ?? 0;
                    //病假
                    $sickLeave         = find([
                            'table'  => "work_holiday",
                            'field'  => "IFNULL(sum(hour),0) as total",
                            'single' => " date_format(startTime, '%Y-%m') = '$month' and stid = '$array[stid]' and state = '已通过' and type = '病假' ",
                        ])['total'] ?? 0;
                    //加班小时数，加班开始时间在本月即记为本月加班
                    $workAddHour = find(array("table" => "work_add", "sum" => "hour", "where" => " stid = '" . $array['stid'] . "' and date_format(timeStart,'%Y-%m') = '$month' and state = '已通过' "));
                    //工作日加班
                    $workAddHourWeekday = find(array("table" => "work_add", "sum" => "hour", "where" => " stid = '" . $array['stid'] . "' and date_format(timeStart,'%Y-%m') = '$month' and state = '已通过' and date_format(timeStart,'%Y-%m-%d') in ('".implode("','",$workDay)."') "));
                    //休息日加班
                    $workAddHourRestDay = find(array("table" => "work_add", "sum" => "hour", "where" => " stid = '" . $array['stid'] . "' and date_format(timeStart,'%Y-%m') = '$month' and state = '已通过' and date_format(timeStart,'%Y-%m-%d') in ('".implode("','",$holiday['holiday'])."') "));
                    //节假日加班
                    $workAddHourFestival = find(array("table" => "work_add", "sum" => "hour", "where" => " stid = '" . $array['stid'] . "' and date_format(timeStart,'%Y-%m') = '$month' and state = '已通过' and date_format(timeStart,'%Y-%m-%d') in ('".implode("','",$holiday['festival'])."') "));
                    //加班调休
                    $exceedWorkHour = $workingHours['workHour'] > $workingHours['lawHour']?$workingHours['workHour'] - $workingHours['lawHour']:0;
                    $compensatoryLeave = $workAddHour - $exceedWorkHour; //总加班时长-超出标准的工时=加班调休时长
                    $data[] = array($list, $month,$array['name'],$department,$clockRule['team'],$workDayResult['dayNum'],$normal,$abnormal,$workingHours['lawHour'],$workingHours['workHour'],$number['late'],$number['early'],$number['is_leave'],$number['miss'],$work_out,$bussiness_trip,$annualLeave,$compassionateLeave,$sickLeave,$workAddHourWeekday,$workAddHourRestDay,$workAddHourFestival,$compensatoryLeave);
                }
            }
            $text = $this->control['name'] . "导出了考勤汇总表";
            $this->logText(["type" => 'clockCollect', "text" => $text]);
            $this->excelOut($title, $data, "考勤汇总表.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'员工编号',
                    'aliasName'=>'员工编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'员工姓名',
                    'aliasName'=>'员工姓名',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'打卡时间',
                    'aliasName'=>'打卡时间',
                    'isMust'=>true,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'员工编号',
                    'aliasName'=>'员工编号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'员工姓名',
                    'aliasName'=>'员工姓名',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'部门',
                    'aliasName'=>'部门',
                ],
                [
                    'columnName'=>'打卡时间',
                    'aliasName'=>'打卡时间',
                ],
                [
                    'columnName'=>'类型',
                    'aliasName'=>'类型',
                ],
                [
                    'columnName'=>'地址',
                    'aliasName'=>'地址',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
            ]
        };
    }
    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = '执行此操作将删除已选定的考勤明细，删除后将无法找回，您确定要这么做吗？';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                $word = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /*行政人事-节假日-批量删除*/
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "权限不足";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                //查询
                $info = query(self::table, " id = '$id' ");
                //删除节假日
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回信息
                $text = "删除了【".self::findStaff($info['stid'])."】的考勤明细：" . $info['signTime'];
                $this->logText(array("type" => self::page, "text" => $text));
                $x++;
            }
            $_SESSION['warn'] = "删除了" . $x . "个考勤明细";
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }
}

